package handel

import (
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"net/http"
	"post/api/gloab"
	"post/api/inits"
	"post/internal/model"
	req2 "post/internal/req"
)

func Reals(c *gin.Context) {
	var req req2.UserReal
	c.ShouldBind(&req)
	var pot model.Pot
	//获取token
	userId, _ := c.Get("userId")

	tx := inits.DB.Debug().Begin()
	tx.Where("user_id = ?", req.DistId).Find(&pot)
	if pot.Follow == "未关注" {
		tx.Table("pots").Where("user_id = ?", req.DistId).Update("follow", "已关注")
		tx.Table("users").Where("id = ?", userId).UpdateColumn("reals", gorm.Expr("reals + ?", 1))
		tx.Table("users").Where("id = ?", req.DistId).UpdateColumn("fs", gorm.Expr("fs + ?", 1))
		c.JSON(http.StatusOK, gin.H{
			"code":    200,
			"message": "关注成功",
			"data":    pot.ID,
		})
		gloab.ClitMap[req.DistId].Data <- []byte("一名用户关注了你")
		tx.Commit()
	} else {
		tx.Table("pots").Where("user_id = ?", req.DistId).Update("follow", "未关注")
		tx.Table("users").Where("id = ?", userId).UpdateColumn("reals", gorm.Expr("reals - ?", 1))
		tx.Table("users").Where("id = ?", req.DistId).UpdateColumn("fs", gorm.Expr("fs - ?", 1))
		c.JSON(http.StatusOK, gin.H{
			"code":    200,
			"message": "取消关注成功",
			"data":    pot.ID,
		})
		tx.Commit()
	}
}
